/**
 * 
 */
package com.yuyi.tools;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.session.mgt.WebSessionKey;

import com.yuyi.model.UserInfo;

/**
 * @author mcb 
 *
 * 2018年8月30日 下午4:58:55 
 */
public class ShiroUtils {
	/**
     * 
     * <p>description: 获取ActiveUser并保存至session中一份</p>
     * @return
     */
	 public static UserInfo getUserInfo(){
	        //从shiro的session中取出UserInfo
	        Subject subject = SecurityUtils.getSubject();
	        //取出身份信息
	        UserInfo userInfo = (UserInfo) subject.getPrincipal();
	        if(userInfo!=null){
	            Session session = subject.getSession();
	            
	            UserInfo user = (UserInfo) session.getAttribute("user");
	            System.out.println("session.getAttribute();"+user);
	            if(user==null){
	                session.setAttribute("user", userInfo);
	            }
	            return userInfo;
	        }else{
	            return null;
	        }
	    }

	    /**
	     * 根据sessionid 获取用户信息
	     * @param sessionID
	     * @param request
	     * @param response
	     * @return
	     */
	    public static UserInfo getUserInfo(String sessionID,HttpServletRequest request,HttpServletResponse response) throws Exception{
	        boolean status = false;
	        SessionKey key = new WebSessionKey(sessionID,request,response);
	        Session se = SecurityUtils.getSecurityManager().getSession(key);
	        Object obj = se.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
	        //org.apache.shiro.subject.SimplePrincipalCollection cannot be cast to com.hncxhd.bywl.entity.manual.UserInfo
	        SimplePrincipalCollection coll = (SimplePrincipalCollection) obj;
	        UserInfo userInfo = (UserInfo)coll.getPrimaryPrincipal();

	        if(userInfo!=null){
	            UserInfo user = (UserInfo) se.getAttribute("user");
	            if(user==null){
	                se.setAttribute("user", userInfo);
	            }
	            return userInfo;
	        }else{
	            return null;
	        }

	    }


}
